import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Select, Row, Col, Affix, Button, InputNumber, message } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;

import 'styles/expense-reimbursement-control/reimbursement/new-standard.scss'
import Chooser from 'components/chooser'
import Selector from 'components/selector'
import Searcher from 'components/searcher'
import searcherData from 'share/searcherData'
import reimburseService from 'containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service'
import errorMessage from 'share/errorMessage'

class NewStandard extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      precision: 2,
      info: {},
      cityPlaceholder: messages('expense-reimbursement-control.key28')/*通用*/,
      userPlaceholder: messages('expense-reimbursement-control.key28')/*通用*/,
    }
  }

  componentDidMount() {
    const { company, defaultSetOfBook } = this.props;
    this.setState({ precision: queryCurrencyPrecision(defaultSetOfBook.baseCurrencyCode || company.baseCurrency) })
  }

  componentWillReceiveProps(nextProps) {
    let { info } = this.state;
    if (nextProps.params.info.standardOID && info.standardOID !== nextProps.params.info.standardOID) {
      this.setState({
        info: nextProps.params.info,
        precision: queryCurrencyPrecision(nextProps.params.info.currencyCode)
      })
    }
  }

  //修改选择的币种
  handleChangeCurrency = (code) => {
    const { getFieldValue, setFieldsValue } = this.props.form;
    let precision = queryCurrencyPrecision(code);
    let amount = getFieldValue('amount');
    if (amount || amount === 0) {
      setFieldsValue({ amount: Number(amount).toFixed(precision) })
    }
    this.setState({ precision })
  };

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { ruleOID, standardOID } = this.props.params;
        values.ruleOID = ruleOID;
        values.standardOID = standardOID;
        this.setState({ loading: true });
        reimburseService.newOrEditStandard(values).then(() => {
          this.setState({ loading: false });
          this.props.close('standard');
          message.success(messages('common.save.success', {name: ""})/*保存成功*/)
        }).catch(e => {
          errorMessage(e.response);
          this.setState({ loading: false })
        })
      }
    })
  };

  onCancel = () => {
    this.props.close()
  };

  //修改关联类型
  handleAssociateTypeChange = (type, value) => {
    const { setFields, getFieldValue } = this.props.form;
    if (type === 'city') {
      setFields({ citys: {value: getFieldValue('citys'), errors: null} });
      this.setState({
        cityPlaceholder: value ? messages('expense-reimbursement-control.key28')/*通用*/ : messages('common.please.select')
      })
    }
    if (type === 'user') {
      setFields({ userGroups: {value: getFieldValue('userGroups'), errors: null} });
      this.setState({
        userPlaceholder: value ? messages('expense-reimbursement-control.key28')/*通用*/ : messages('common.please.select')
      })
    }
  };

  //渲染关联类型
  renderAssociateType = (type) => {
    return (
      <Select onChange={value => this.handleAssociateTypeChange(type, value)} getPopupContainer={triggerNode => triggerNode.parentNode}>
        <Option value={1}>{messages('expense-reimbursement-control.key71')/*包含*/}</Option>
        <Option value={0}>{messages('expense-reimbursement-control.key72')/*不包含*/}</Option>
      </Select>
    )
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { company, user, defaultSetOfBook } = this.props;
    const { loading, precision, info, cityPlaceholder, userPlaceholder } = this.state;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12, offset: 1 },
    };
    let searcherItem = searcherData['city_level'];
    searcherItem.key = 'levelOID';
    return (
      <div className="new-standard">
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('expense-reimbursement-control.key27')/*适用城市*/}>
            <Row>
              <Col span={8}>
                <FormItem>
                  {getFieldDecorator('cityAssociateType', {
                    initialValue: info.cityAssociateType || info.cityAssociateType === 0 ? info.cityAssociateType : 1
                  })(
                    this.renderAssociateType('city')
                  )}
                </FormItem>
              </Col>
              <Col offset={1} span={15}>
                <FormItem>
                  {getFieldDecorator('citys', {
                    rules: [{
                      required: getFieldValue('cityAssociateType') === 0,
                      message: messages('common.please.select')
                    }],
                    initialValue: info.citys
                  })(
                    <Searcher searcherItem={searcherItem}
                              listExtraParams={{deleted: false, page: 0, size: 2000}}
                              labelKey="levelName"
                              showDetail
                              newline
                              placeholder={cityPlaceholder}/>
                  )}
                </FormItem>
              </Col>
            </Row>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('expense-reimbursement-control.key29')/*适用人员*/}>
            <Row>
              <Col span={8}>
                <FormItem>
                  {getFieldDecorator('userAssociateType', {
                    rules: [{
                      required: getFieldValue('userAssociateType') === 0,
                      message: messages('common.please.select')
                    }],
                    initialValue: info.userAssociateType || info.userAssociateType === 0 ? info.userAssociateType : 1
                  })(
                    this.renderAssociateType('user')
                  )}
                </FormItem>
              </Col>
              <Col offset={1} span={15}>
                <FormItem>
                  {getFieldDecorator('userGroups', {
                    rules: [{
                      required: getFieldValue('userAssociateType') === 0,
                      message: messages('common.please.select')
                    }],
                    initialValue: info.userGroups
                  })(
                    <Chooser type="user_group"
                             valueKey="userGroupOID"
                             labelKey="name"
                             newline
                             placeholder={userPlaceholder}/>
                  )}
                </FormItem>
              </Col>
            </Row>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.amount')/*金额*/}>
            <Row>
              <Col span={11}>
                <FormItem>
                  {getFieldDecorator('currencyCode', {
                    initialValue: info.currencyCode || defaultSetOfBook.baseCurrencyCode || company.baseCurrency
                  })(
                    <Selector
                      type="currency"
                      params={{
                        language: 'zh_cn',
                        userOId: user.userOID,
                        setOfBooksId: defaultSetOfBook.setOfBooksId
                      }}
                      filter={item => item.enable}
                      showSearch
                      placeholder={messages("common.please.select")}
                      allowClear={false}
                      onChange={this.handleChangeCurrency}
                    />
                  )}
                </FormItem>
              </Col>
              <Col span={12} offset={1}>
                <FormItem>
                  {getFieldDecorator('amount', {
                    initialValue: info.amount
                  })(
                    <InputNumber style={{width: '100%'}}
                                 placeholder={messages('expense-reimbursement-control.key30')/*不限制*/}
                                 precision={precision}
                                 min={0}/>
                  )}
                </FormItem>
              </Col>
            </Row>
          </FormItem>
          <Affix offsetBottom={0} className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages('common.save'/*保存*/)}
            </Button>
            <Button onClick={this.onCancel} className="btn-cancel">
              {messages('common.cancel')/*取消*/}
            </Button>
          </Affix>
        </Form>
      </div>
    )
  }
}

NewStandard.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    languageList: state.login.languageList,
    language: state.main.language,
    user: state.login.user,
    defaultSetOfBook: state.cache.defaultSetOfBook
  }
}

const WrappedNewStandard = Form.create()(NewStandard);

export default connect(mapStateToProps)(WrappedNewStandard)
